package cn.com.callback;
import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.DateFormat
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;

import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;

/**
 *
 * @Title: ApiBPCreate
 * @Description:深圳宝安排水系统工单录入同步接口--外部接口
 * @author: chieh
 * @date 2020-11-08 21:28:00
 *
 */

public class ApiBPCreate implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(ApiBPCreate.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		//response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		long startTime = System.currentTimeMillis();
		
		String reJson = null;
		long endTime = 0;
		String dealMessage = "";
		
		JSONArray resArray = new JSONArray();
		JSONObject resObject = new JSONObject();
		
		//生成随机36位id
		String Relation_ID = UUID.randomUUID().toString();
		log.debug("objective_guid:" + Relation_ID);
		
		//生成小程序工单编号
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Calendar calendar = Calendar.getInstance();
		String workorderid = df.format(calendar.getTime());
		log.debug("workorderid:" + workorderid);
		
		try {
			
			// 调用处理信息
			//JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			
			// usetype pid 排序问题
			JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArraytemp: " + jsonArraytemp);
			
			JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
			log.debug(dataObjecttemp);
			String companytpyetemp = GetJV(dataObjecttemp, "companytpye");
			String business1temp = GetJV(dataObjecttemp, "business1");
			String business2temp = GetJV(dataObjecttemp, "business2");
			String business3temp = GetJV(dataObjecttemp, "business3");
			String isstreettemp = GetJV(dataObjecttemp, "isstreet");
			String addresstemp = GetJV(dataObjecttemp, "address");
			String descriptiontemp = GetJV(dataObjecttemp, "description");
			String locationxtemp = GetJV(dataObjecttemp, "locationx");
			String locationytemp = GetJV(dataObjecttemp, "locationy");
			String atttemp = GetJV(dataObjecttemp, "att");
			String openidtemp = GetJV(dataObjecttemp, "openid");
			
			log.debug("companytpye:"+companytpyetemp);
			log.debug("business1:"+business1temp);
			log.debug("business2:"+business2temp);
			log.debug("business3:"+business3temp);
			log.debug("isstreet:"+isstreettemp);
			log.debug("address:"+addresstemp);
			log.debug("description:"+descriptiontemp);
			log.debug("locationx:"+locationxtemp);
			log.debug("locationy:"+locationytemp);
			log.debug("att:"+atttemp);
			log.debug("openid:"+openidtemp);

			String replaceString ="[{\"companytpye\":\""+companytpyetemp+"\",\"business1\":\""+business1temp+"\",\"business2\":\""+business2temp+"\",\"business3\":\""+business3temp+"\",\"isstreet\":\""+isstreettemp+"\",\"address\":\""+addresstemp+"\",\"description\":\""+descriptiontemp+"\",\"locationx\":"+locationxtemp+",\"locationy\":"+locationytemp+",\"att\":"+atttemp+",\"openid\":\""+openidtemp+"\"}]";
			//[{"companytpye":"38982B","business1":"M7JFZM","business2":"BB5D6F","business3":"D6A37C","isstreet":"96F3EE","address":"广东省深圳市宝安区万丰中路471-4号","description":"咸井163号沟通堵塞","locationx":22.725843,"locationy":113.826836,"att":[{"filename":"kqk4o39","url":"https://callcenterwx.szbaps.com/ngs/fs/get?file=applets/20231119/9255ce2a1c2c4e209bb75a5c289fa5eb.jpg"},{"filename":"7y1cihk","url":"https://callcenterwx.szbaps.com/ngs/fs/get?file=applets/20231119/e6809d4e51394bb08a2cd5559cb5793b.jpg"}],"openid":"oJG5P5Z983vrrCo5vLqVLwSIl9e8"}]
			log.debug("replaceString:"+replaceString);
			
			//鉴权加密处理--验证密码
			JSONObject checkJson = signUtil.CheckSign(inObject,replaceString);
			log.debug("checkJson: " + checkJson);

			if (checkJson != null) {
				log.debug("[签名校验异常-返回信息]:" + checkJson);
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:"+signUtil.jsonObjectToMap(checkJson)+"),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			} else {
				log.debug("[签名校验成功]");
				// 校验成功
				//todo 业务逻辑
			}
			
			//data 获取参数openid
			JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArray: " + jsonArray);
			String openid= jsonArray.getJSONObject(0).get("openid");//openid
			
			String companytpye= jsonArray.getJSONObject(0).get("companytpye");//单位类别
			String business1= jsonArray.getJSONObject(0).get("business1");//业务类型			
			String business2= jsonArray.getJSONObject(0).get("business2");//水务设施			
			String business3= jsonArray.getJSONObject(0).get("business3");//投诉内容（业务类型为投诉必填）			
			String isstreet= jsonArray.getJSONObject(0).get("isstreet");//行政街道			
			String address= jsonArray.getJSONObject(0).get("address");//详细地址			
			String description= jsonArray.getJSONObject(0).get("description");//问题描述			
			String locationx= jsonArray.getJSONObject(0).get("locationx");//X坐标			
			String locationy= jsonArray.getJSONObject(0).get("locationy");//Y坐标
			
			String att= jsonArray.getJSONObject(0).get("att");//图片			
			
			log.debug("解析信息-companytpye：" + companytpye + " business1：" + business1 + " business2：" + business2+ " business3：" + business3+ " isstreet：" + isstreet+ " address：" + address+ " description：" + description+" locationx：" + locationx+ " locationy：" + locationy+ " att" + att);
			
			//必填项校验
			if (isNull(business1) || isNull(business2) || isNull(isstreet) || isNull(address) || isNull(description) ||  isNull(locationx)|| isNull(locationy)|| isNull(att)) {
				dealMessage = isNullMSG("business1", business1) + isNullMSG("business2", business2) + isNullMSG("isstreet", isstreet) + isNullMSG("address", address) + isNullMSG("description", description)+ isNullMSG("locationx", locationx)+ isNullMSG("locationy", locationy)+isNullMSG("att", att);
				endTime = System.currentTimeMillis();
				log.warn(dealMessage);
				reJson = "{\"result\":\"0\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			} else {
				//坐标转换，腾讯地图转换成百度地图坐标
				String str=map_tx2bd(locationx, locationy);
				locationx=str.substring(0, str.indexOf(","));
				locationy=str.substring(locationx.length()+1, str.length());
				
				
				//处理附件图片
				JSONArray arrJsonArray = new JSONArray(att);
				int arrInt = arrJsonArray.length();
				log.debug("接入图片数量:" + arrInt);
				for (int i = 0; i < arrInt; i++) {
					//JSONObject arrJson = arrJsonArray.getJSONObject(i);
					//图片信息
					String url = arrJsonArray.getJSONObject(i).get("url");//附件的 URL
					String filename = arrJsonArray.getJSONObject(i).get("filename");//文件名称，路径
					log.debug("附件的URL:"+url);
					log.debug("文件名称路径:"+filename);
					def urlresult=eliteBean.update("INSERT INTO  rm_uploadrecord (guid, objectiveID, path, name, operationtime,  operator, filesuffix, filedesc,type) VALUES (Newid(),'" + Relation_ID + "','" + url + "','" + filename + "',getdate() ,'小程序','','',5)", dataSourceID);
					log.debug("图片更新sql结果:" + urlresult);
				}
				
				//处理客户
				def customerresult = eliteBean.chaxun_sql("select top 1 CUSTOMER_GUID,customername as customername,mobile as mobile from CUSTOMER  where wechatid='"+openid+"' ORDER BY CREATEDDATE asc", "dataSource");
				log.debug("查看客户是否存在sql结果:" + customerresult);
				String old_customer_guid = null;
				String customername = null;
				String mobile = null;
				if(customerresult.size() > 0) {
					old_customer_guid = customerresult.get(0).get("CUSTOMER_GUID");
					customername = customerresult.get(0).get("customername");
					mobile = customerresult.get(0).get("mobile");
				}else{
					endTime = System.currentTimeMillis();
					reJson = "{\"result\":\"0\",\"resultmessage\":\"处理失败(当前账号无授权注册！),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
					return reJson;
				}
				//处理行政区域 与街道
				String PCode_ID = null;
				String yygh_codeid= null;
				def PCoderesult = eliteBean.chaxun_sql("select PCode_ID from c_codetables where  code_id='"+isstreet+"' and Use_Type='街道'", "dataSource");
				if(PCoderesult.size() > 0) {
					PCode_ID = PCoderesult.get(0).get("PCode_ID");
					def yygh_codeidresult = eliteBean.chaxun_sql("select yygh_codeid from c_codetables where  code_id='"+PCode_ID+"' and Use_Type='行政区域'", "dataSource");
					
					if(yygh_codeidresult.size() > 0) {
						yygh_codeid = yygh_codeidresult.get(0).get("yygh_codeid");
					}
				}
							
				//处理工单
				String workordertype="";//工单类型（个人、单位）
				if(companytpye=="") {
					workordertype="个人";
				}else {
					workordertype="单位";
				}
				log.debug("报障类型：" + workordertype);
				String[] data = new String[4];
				data[0] = "insert into  TABCCONSULTWORKORDER (RELATION_ID,business_source,company_tpye,reportingname,phone_number,business_type_1,business_type_2, business_type_3,location_x,location_y,address,description,administrative,isstreet,_subunit)VALUES('" + Relation_ID + "','3E98AF','" + companytpye + "','"+customername+"','"+mobile+"','"+business1+"','"+business2+"','"+business3+"','"+locationx+"', '"+locationy+"', '"+address+"', '"+description+"','"+PCode_ID+"','"+isstreet+"','"+yygh_codeid+"')";
				data[1] = "Insert Into Objective (objective_guid, Objectivetype_Id, Handleby_Id, Handlegroup_Id, Priority_Id, Expireddate, Customer_Guid, Objectivestatus,comments, Createdby, Createddate, Modifiedby, Modifieddate, Workorderframe_Id, Category, Forecastdate, Workorderid, Objectivesubstatus, Map_Id, Curstep_Id_Map)Values ('" + Relation_ID + "' , 'NPYG4A', Null, 'TEAM01', 'NORMAL', getdate(),'" + old_customer_guid + "','OPEN','"+description+"','SELITE', getdate(), 'SELITE',getdate(), 'MYI3EW', 'CASE1', getdate(),'"+workorderid+"' , 'OPEN ', 'MYI3EW', 'O70W2B')";
				data[2] ="Insert Into Elitetask(Elitetask_Guid,  Objective_Guid, Objectivetype_Id, Expectstarttime, Expectendtime, Priority, Handleby_Id, Handlegroup_Id, Createdby, Createddate, Modifiedby, Modifieddate, Comments,Customer_Guid, Customerlevel, Localtrycount, Curstepstatus, Curstep_Id, Stepforecastdate, Curstep_Id_Map, Map_Id, Objectivesubstatus, Obflag) Values (Newid(), '" + Relation_ID + "','NPYG4A',getdate() ,getdate() ,'NORMAL', Null,'SYSTEM','SELITE',  getdate() ,'SELITE',getdate() ,'"+description+"', '" + old_customer_guid + "', Null, '0', 'OPEN ', 'O70W2B',  getdate() , 'O70W2B', 'MYI3EW', 'OPEN', '0')";
				data[3] ="Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate, Workorderstepid, Stepexpired, Child_Id, Stepstart, Cur_Expiredflag, Cur_Expiredlen, Event_Guid, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime)Values('" + Relation_ID + "' , Newid(), 'SELITE', 'SYSTEM', '', '', 'CLOSE', '',  getdate() , Null,  getdate() , Null,  getdate() , '0', '0', '', 'O70W2B', 'O70W2B', getdate(), getdate())";
				log.debug("当前执行更新结果SQL:" + data.toString());
				def dataresult = eliteBean.updateBatch(data, dataSourceID);
				log.debug("当前执行更新结果SQL结果:" + dataresult.toString());
			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"创单成功处理失败(" + e.getMessage() + ")\"}";

		}

		resObject.put("workorderid",workorderid);
		resArray.put(resObject);
		
		endTime = System.currentTimeMillis();
		outData = "{\"resultcode\":\"1\",\"resultmessage\":\"创单成功处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+resArray+"}";
		return outData;
	}

	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
			Rev_Value = String.valueOf(inJson.getDouble(getKey));
			} catch (Exception e1) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e2) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e3) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e4) {
						Rev_Value = "";
					}}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
	/**
	 * 坐标转换，腾讯地图转换成百度地图坐标
	 *
	 * @param lat 腾讯纬度
	 * @param lon 腾讯经度
	 * @return 返回结果：经度,纬度
	 */
	public static String map_tx2bd(String a, String b) {
		double bd_lat;
		double bd_lon;
		double x_pi = 3.14159265358979324;
		//double x = b, y = a;
		
		double x = Double.valueOf(a);
		double y = Double.valueOf(b);
		double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		bd_lon = z * Math.cos(theta) + 0.0065;
		bd_lat = z * Math.sin(theta) + 0.006;

		log.debug("bd_lat:" + bd_lat);
		log.debug("bd_lon:" + bd_lon);
		return bd_lon + "," + bd_lat;
	}

}